package com.hmall.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.pojo.Item;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.service.IItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {
    @Autowired
    private ItemMapper itemMapper;

    @Override
    public PageDTO<Item> listPage(Integer page, Integer size) {
        //1. 设置当前页与页面大小
        Page<Item> pages = new Page<>(page, size);

        //2. 创建分页需要条件
        QueryWrapper queryWrapper = new QueryWrapper();

        //3. 调用selectPage方法实现分页，分页的结果会被封装到Pages对象中
        itemMapper.selectPage(pages, queryWrapper);

        PageDTO<Item> pageDTO = new PageDTO<>();
        pageDTO.setTotal(pages.getTotal());
        pageDTO.setList(pages.getRecords());
        return pageDTO;
    }

    /**
     * 提交订单 - 扣减库存
     * num <= 库存数量、商品状态=1、销量+num、更新时间
     *
     * @param itemId
     * @param num
     */
    @Override
    public void stock(Long itemId, Integer num) {
        LambdaQueryWrapper<Item> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Item::getId, itemId).eq(Item::getStatus, 1);
        Item item = itemMapper.selectOne(queryWrapper);

        if (item == null) {
            throw new RuntimeException("商品不存在或已下架");
        }
        if (item.getStock() < num) {
            throw new RuntimeException("库存不足");
        }

        LambdaUpdateWrapper<Item> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Item::getStock, item.getStock() - num)
                .set(Item::getSold, item.getSold() + num)
                .set(Item::getUpdateTime, LocalDateTime.now())
                .eq(Item::getId, itemId);

        int updateCount = itemMapper.update(null, updateWrapper);
        if (updateCount == 0) {
            throw new RuntimeException("库存扣减失败");
        }
    }
}
